<!DOCTYPE html>
<html>
<head>
    <title>E姐姐文案生成</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
</head>
<body style="background-color:#fffbf6">
    <!-- 登录状态显示 -->
    <div style="text-align:right; padding:10px; background-color:#f0f0f0; border-bottom:1px solid #ddd;">
        {% if session.get('logged_in') %}
            <span style="color:green; font-weight:bold;">已登录: {{ session.get('username') }}</span>
            <a href="{{ url_for('logout') }}" style="margin-left:15px; color:#666; text-decoration:none;">退出</a>
        {% else %}
            <span style="color:red; font-weight:bold;">未登录</span>
            <a href="{{ url_for('login') }}" style="margin-left:15px; color:#666; text-decoration:none;">登录</a>
        {% endif %}
    </div>
    
    {% include 'top_bar_ej.html' %}
    <div id="container" style="display:flex;background-color:#fffbf6 ;text-align: center; justify-content: center; width: 400px;flex-wrap: wrap; ">
        <div id="date" style="color:rgb(171, 176, 179); font-size:20px; margin-bottom: 10px;"></div>
    </div>

    <div><h3>· 选择文件</h3>
        <label for="date_or_prd">
            <h4><input type='radio' name="fn" value="1" onclick=hideOrDisplayEndDate() checked> 文件1 <input type='radio' name="fn" value="2" onclick=hideOrDisplayEndDate()> 文件2</h4>            
        </label>
    </div>

    <div><h3>· 选择单日还是多日</h3>
        <label for="date_or_prd">
            <h4><input type='radio' name="date_or_prd" value="0" onclick='hideOrDisplayEndDate();refresh();' checked> 单日 <input type='radio' name="date_or_prd" value="1" onclick='hideOrDisplayEndDate();refresh();'> 多日</h4>            
        </label>
    </div>

    <div><h3><span id="start_date_txt">· 请选择日期</span>  <input id='start_date' type='date' onchange='sameEndDate();refresh();'></h3></div>    
    <div id="end_date_block"><h3>· 请选择结束日  <input id='end_date' type='date' onchange='refresh();'></h3></div>

    <div><h3>· 生成文件类型</h3>
        <label for="date_or_prd">
            <h4><input type='radio' name="file_types" value="img_txt" onclick='refresh();' checked> 仅图片及文本 <input type='radio' name="file_types" value="img_txt_video" onclick='refresh();' > 图片+文本+视频（需要时间较长）</h4>            
        </label>
    </div>

    <hr>
    <div id="prompt" class="prompt">
    </div>
    <div>
        <button id="submit" onclick=submit()>生成文案及图片/视频</button>&nbsp;&nbsp;<button id="refresh" onclick="refresh();">刷新看是否已完成</button>
    </div>

    <div id="resDateList" style="margin-top:30px;"></div>

   

    <div id="dl" style="margin-top:10px;display: none;"><a href="{{ url_for('zip_and_download') }}" onclick="hideDownload()">下载文件</a></div>
    <!-- <div id="dl" style="margin-top:10px;display: none;" onclick="downloadFile()">点击下载文件</div> -->

    
    <script src="../static/js/common.js"></script>
    <script>
        let dates;
        document.addEventListener('DOMContentLoaded',function(){
            showDateandWeekDay();
            selectToday('start_date','date');
            selectToday('end_date','date');
            
            hideOrDisplayEndDate();
            refresh();
        })
    
        function refresh(){
            const fileTypes=document.querySelector('input[name="file_types"]:checked').value;
            const startDate=document.getElementById('start_date').value;
            const endDate=document.getElementById('end_date').value;
            const resDateList=document.getElementById('resDateList');
            resDateList.innerHTML='';
            const data={
                'file_types':fileTypes,
                'start_date':startDate,
                'end_date':endDate
            }
            fetch('/check_riyun_files',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                    },
                body:JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if(data['res']==='ok'){
                        console.log(data);
                        
                        const sel=document.createElement('select');
                        data['data'].forEach(ele => {        
                            zipAndDownload(ele);             
                            // const opt=document.createElement('option');
                            // opt.value=ele;
                            // opt.text=ele;
                            // opt.addEventListener('change',zipAndDownload(ele))
                            // sel.appendChild(opt);           
                                             
                        });
                        // resDateList.appendChild(sel);
                    }else{
                        resDateList.innerHTML='该日期还没有生成日运相关文件';
                    }
                    
                })
                .catch(error=>{
                    console.log(error);
                })

        }

        function zipAndDownload(dateInput){
            const resDateList=document.getElementById('resDateList');
            const dlDiv=document.createElement('div');
            const a=document.createElement('a');
            const baseUrl='{{ url_for("zip_and_download") }}';
            a.innerText=`${dateInput}的文件下载`;
            a.href=`${baseUrl}?date=${dateInput}`;
            dlDiv.appendChild(a);
            resDateList.appendChild(dlDiv);
        }
    
        function hideDownload(){
            const dl=document.getElementById('dl');
            const prompt=document.getElementById('prompt');
            prompt.innerText='';
            prompt.style.display='block';
            dl.style.display='none';
        }

        function sameEndDate(){
            document.getElementById('end_date').value=document.getElementById('start_date').value;
        }

        function showDateandWeekDay(){
            const dateBlock=document.getElementById('date');
                const today=new Date();
                const year = today.getFullYear();
                const month = String(today.getMonth() + 1).padStart(2, '0');
                const day = String(today.getDate()).padStart(2, '0');
                // 获取星期几的数值
                const dayOfWeek = today.getDay();
                // 将星期几的数值转换为中文
                let weekDayChinese = '';
                switch (dayOfWeek) {
                case 0:
                    weekDayChinese = '星期日';
                    break;
                case 1:
                    weekDayChinese = '星期一';
                    break;
                case 2:
                    weekDayChinese = '星期二';
                    break;
                case 3:
                    weekDayChinese = '星期三';
                    break;
                case 4:
                    weekDayChinese = '星期四';
                    break;
                case 5:
                    weekDayChinese = '星期五';
                    break;
                case 6:
                    weekDayChinese = '星期六';
                    break;
                default:
                    weekDayChinese = '未知';
                }
                dateDisplay=`${year} 年 ${month} 月 ${day} 日
                            ${weekDayChinese}`; 
                dateBlock.innerText=dateDisplay;
        }

        function hideOrDisplayEndDate(){
            const dateOrPrd=document.querySelector('input[name="date_or_prd"]:checked').value;
            const endDateBlock=document.getElementById('end_date_block');
            const startDateTxt=document.getElementById('start_date_txt');

            // 单日
            if(dateOrPrd==='0'){            
                endDateBlock.style.display='None';
                startDateTxt.innerText='· 请选择日期'
            // 多日
            }else{
                endDateBlock.style.display='block';
                startDateTxt.innerText='· 请选择起始日'
            }
        }
        
        function submit(){
            const fileTypes=document.querySelector('input[name="file_types"]:checked').value;
            const startDate=document.getElementById('start_date').value;
            const endDate=document.getElementById('end_date').value;
            const fnNum=document.querySelector('input[name="fn"]:checked').value;
            const prompt=document.getElementById('prompt')
            // prompt.innerText='正在处理，请等待。'
            console.log(startDate,endDate)   
            if(fileTypes==='img_txt'){
                prompt.innerText='正在生成日运图片及文本，请等待。'
            }else{
                prompt.innerText='正在生成日运图片、文本及视频 ，时间较长，请等待。'
            }

            const data={
                fn_num:fnNum,
                start_date:startDate,
                end_date:endDate,
                file_types:fileTypes
            }
            // console.log('submit data:',data);

            fetch('/generate_riyun_file',{
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                    },
                body:JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    res=data.res;      
                    console.log(res)              
                    if(res==='ok'){
                        // document.getElementById('dl').style.display='block';
                        refresh();
                        console.log('new zip back')
                        // 修改提示只有在没有错误发生时才生效
                        if (prompt.innerText === '正在生成日运图片、文本及视频 ，时间较长，请等待。') {
                            prompt.style.display = 'none';
                        }
                    }else{
                        console.log('error',data.error)
                        prompt.innerText = data.error;
                        alert('生成错误'+'\n'+data.error)
                    }
                    

                })
                .catch(error => {
                    console.log('Error:',error);
                    prompt.innerText = error;
                    document.getElementById('dl').style.display='none';});
            

        }

    
    

    </script>
</body>
